package br.usp.pcs.basys.event;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import br.usp.pcs.basys.Job;
import br.usp.pcs.basys.engine.IResources;

public class JobCompletion extends ComputerSystemEvent {

	public JobCompletion(Job job, Date date, IResources resources) {
		super(job, date, resources);
	}

	@Override
	List<ActionResult> run() {
		List<ActionResult> result = new ArrayList<ActionResult>();
		resources.releaseProcessor();
		advanceProcessorQueue();
		ActionResult advanceProcessorQueue = new ActionResult() {
			public String toString() {
				return "Avdanced Processor Queue";
			}
		};
		long size = job.getRequiredMemorySpace();
		resources.deallocate(size);
		advanceMemoryQueue();
		ActionResult advanceMemoryQueue = new ActionResult() {
			public String toString() {
				return "Avdanced Memory Queue";
			}
		};
		result.add(advanceProcessorQueue);
		result.add(advanceMemoryQueue);
		return result;
	}

	private void advanceMemoryQueue() {
		MemoryRequest memoryRequest = resources.pollMemoryQueue();
		if (memoryRequest != null) {
			memoryRequest.setDate(date);
			resources.add(memoryRequest);
		}

	}

	private void advanceProcessorQueue() {
		ProcessorRequest processorRequest = resources.pollProcessorQueue();
		if (processorRequest != null) {
			processorRequest.setDate(date);
			resources.add(processorRequest);
		}
	}

}
